package org.atlantis.grosbeak.lang.inject;

import java.lang.reflect.Field;

import org.atlantis.grosbeak.castor.Castors;
import org.atlantis.grosbeak.lang.Exceptions;

/**
 * 直接给字段注入值（不采用Setter方法）。
 * 
 * @author <a href="mailto:seenoevil.cn@gmail.com">SeeNoEvil</a>
 * 
 */
public class FieldInjector implements Injecting {

	private Field field;

	public FieldInjector(Field field) {
		this.field = field;
		this.field.setAccessible(true);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.atlantis.grosbeak.lang.inject.Injecting#inject(java.lang.Object,
	 * java.lang.Object)
	 */
	public void inject(Object target, Object value)
			throws FailToInjectException {
		Object val = null;
		try {
			val = Castors.me().castTo(value, field.getType());
			field.set(target, val);
		} catch (Exception e) {
			throw Exceptions.makeThrow(FailToInjectException.class,
					"Fail to set '%s' to '%s.%s', because [%s].", value, field
							.getDeclaringClass().getName(), field.getName(), e
							.getMessage());
		}
	}
}
